package com.chunxuan.langquan.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.support.util.Logg;
import com.ruitu.arad.base.BaseFragment;

import java.util.List;
import java.util.Locale;

// 首页
public class Home4Fragment extends BaseFragment {
    //    private Banner banner;
    private static Home4Fragment fragment;
    private RelativeLayout rl_3,rl_search;// 精选文章,报告解读,下单,搜索
    private ImageView iv_notice;// 消息
    private TextView  vUnreadCount;

    private LocationManager lm;

    public Home4Fragment() {

    }

    public static Home4Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home4Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    }

    private void initGps() {
        // 从gps获取最近的定位信息
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location lc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        updateShow(lc);
        //设置间隔两秒获得一次gps定位信息
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // 当gps定位信息发生改变时,更新定位
                updateShow(location);
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {
            }

            @Override
            public void onProviderEnabled(String provider) {
                // 当gpsLocationProvider可用时,更新定位
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                updateShow(lm.getLastKnownLocation(provider));
            }

            @Override
            public void onProviderDisabled(String s) {
                updateShow(null);
            }
        });
    }

    // 定义更新显示的方法
    private void updateShow(final Location location) {
        if (location != null) {
            StringBuilder sb = new StringBuilder();
            sb.append("当前位置定位信息:\n");
            sb.append("经度:" + location.getLongitude() + "\n");
            sb.append("维度:" + location.getLatitude() + "\n");
            sb.append("海拔:" + location.getAltitude() + "\n");
            sb.append("速度:" + location.getSpeed() + "\n");
            sb.append("方位:" + location.getBearing() + "\n");
            sb.append("时间:" + location.getTime() + "\n");
            sb.append("定位精度:" + location.getLongitude() + "\n");
//            Logg.i("sb.toString() = " + sb.toString());
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getAddress(location);
                }
            }).start();
        } else {
//            tv_city.setText("定位失败");
            Logg.i("定位失败...");
        }
    }

    List<Address> result = null;

    // 获取地址信息
    private List<Address> getAddress(Location location) {
        try {
            if (location != null) {
                Geocoder gc = new Geocoder(getActivity(), Locale.getDefault());
                result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                for (int i = 0; i < result.size(); i++) {
                    Logg.i("result " + i + " = " + result.get(i).toString());
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String city = "";
                        try {
                            city = result.get(0).getSubAdminArea();
                            if (TextUtils.isEmpty(city)) {
                                city = result.get(0).getLocality();
                            }
                            if (TextUtils.isEmpty(city)) {
                                city = "定位中";
                            }
//                            tv_city.setText(city);
                        } catch (Exception e) {
                            e.printStackTrace();
//                            tv_city.setText("定位失败");
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home1, container, false);
//        banner = v.findViewById(R.id.banner);// Banner布局
        rl_3 = v.findViewById(R.id.rl_3);
        iv_notice = v.findViewById(R.id.iv_notice);
//        tv_city = v.findViewById(R.id.tv_city);
        rl_search = v.findViewById(R.id.rl_search);
        vUnreadCount = v.findViewById(R.id.vUnreadCount);

        setListeners();

//        reqBannerList();// 请求banner列表
        initGps();// 开始定位
        return v;
    }

    private void setListeners() {
        setOnClickListener(rl_3,  iv_notice,  rl_search);
    }

    @Override
    public void onClick(View v) {
        if (v == rl_search) {// 搜索
//            startActivity(SearchActivity.class);
        }
        if (v == rl_3) {//
//            startActivity(ArticleListActivity.class);
        }
        if (v == iv_notice) {// 消息
//            startActivityForResult(new Intent(getActivity(), MsgListActivity.class), 1001);
        }
    }

    // 请求首页banner
//    private Disposable reqBannerList() {
//        return APIRetrofit.getDefault().reqHomeBannerList("1")
//                .compose(RxUtil.<BaseResult2<List<Banner>>>subIoObMain())
//                .subscribe(new Consumer<BaseResult2<List<Banner>>>() {
//                    @Override
//                    public void accept(BaseResult2<List<Banner>> listBaseResult2) throws Exception {
//                        hideProgress();
//                        if (listBaseResult2.isSuccess()) {
//
//                        } else {
//
//                        }
//                        bannerList = listBaseResult2.getData();
//                        adapter.notifyDataSetChanged();
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
//                        throwable.printStackTrace();
//                    }
//                });
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}